<template>
  <avue-crud
    ref="gameCompanyRef"
    :table-loading="tableLoading"
    v-model="form"
    :option="option"
    @refresh-change="getList"
    @row-save="rowSave"
    @row-update="rowUpdate"
    @row-del="rowDel"
    :data="data"
    :page="page"
    @size-change="sizeChange"
    @current-change="currentChange"
    @search-change="searchChange"
    @search-reset="searchReset"
  >
  </avue-crud>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import gameCompany from "@/options/gameCompany";
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getCompanyList,
  addCompany,
  editCompany,
  delCompany,
} from "@/apis/admin";

const option = gameCompany;
const data = ref([]);
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
});

const sizeChange = (val) => {
  page.pageSize = val;
  getList();
};
const currentChange = (val) => {
  page.currentPage = val;
  getList();
};
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  getList();
  done();
};
const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  getList();
};
const form = ref({});
const tableLoading = ref(false);

const rowSave = async (row, done, loading) => {
  const res = await addCompany.post("", row);
  if (res.code == 200) {
    done();
    ElMessage.success("添加成功!");
    getList();
  } else {
    ElMessage.error("添加失败!");
  }
};
const rowDel = (row, index, done) => {
  ElMessageBox.confirm("此操作将永久删除该游戏公司, 是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    delCompany.post("", { id: row.id }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功！");
        getList();
      } else {
        ElMessage.error("删除失败!");
      }
    });
  });
};
const rowUpdate = async (row, index, done, loading) => {
  const res = await editCompany.post("", row);
  if (res.code == 200) {
    done();
    ElMessage.success("编辑成功!");
    getList();
  } else {
    ElMessage.error("编辑失败!");
  }
};

const getList = () => {
  tableLoading.value = true;
  getCompanyList
    .post("", {
      searchInfo: page.searchInfo,
      page: page.currentPage,
      pageSize: page.pageSize,
    })
    .then((res) => {
      if (res.code == 200) {
        page.total = res.data.total;
        data.value = res.data.list;
      }
      tableLoading.value = false;
    });
};

onMounted(() => {
  getList();
});
</script>
